<template>
  <!--页面搭建-付张祥-->
  <layout-card
    v-model="search"
    :filters="ismapOptions"
    headline="信息列表"
    headtitle=" "
    :hasButton="true"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <template #action>
      <el-button
        type="primary"
        @click="handleCreate('export')"
        :disabled="tabledata.length === 0"
      >下载</el-button
      >
      <el-button type="primary" @click="() => openAddDialog()"
      >新建</el-button
      >
    </template>
    <table-common
      :height="tableHeight"
      :columns="mapListColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="tabledata"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
      @sort-change="sortChange"
    >
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleCheck(row)" link type="primary">查看</el-button>
        <el-button class="link-btn" v-if="row?.isState === '0' || row?.isState === '1'" @click="handleEdit(row)" link type="primary">编辑</el-button>
        <el-button class="link-btn" v-if="row?.isState === '0' && row?.isFile === '是'" @click="handleExamine(row)" link type="primary">审核</el-button>
        <el-popconfirm
          v-if="row?.isFile === '否'"
          title="是否删除?"
          confirmButtonText="确定"
          cancelButtonText="取消"
          @confirm="() => DeletRow(row)"
        >
          <template #reference>
            <el-button class="link-btns" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <!-- 新增弹框 -->
  <Add :visible="centerDialogVisibleAdd" :info="info" @cancel="cancelAdd" @showAdd="handleShowAdd"></Add>
  <!-- 编辑 -->
  <Edit :visible="centerDialogVisibleEdit" :info="info" :data="data" @cancel="cancelEdit" @showAdd="handleShowEdit"></Edit>
  <!-- 查看 -->
  <Check :visible="centerDialogVisibleCheck" :info="info" :data="data" @cancel="cancelCheck" @showAdd="handleShowCheck"></Check>
  <!-- 审核 -->
  <Examine :visible="centerDialogVisibleExamine" :info="info" :data="data" @cancel="cancelExamine" @showAdd="handleShowExamine"></Examine>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, onBeforeMount, nextTick } from "vue";
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import {deleteTrainingRecords, getListPage, getUnitList, exportPageList} from "@/api/secure/trainingRecords";
import Add from './add.vue'
import Edit from './edit.vue'
import Check from './check.vue'
import Examine from './examine.vue'
import {
  houseImport,
  getUserInfo,
} from "@/api/eqpt/houseManger";
import { mapListColumns } from "@/views/secure/archives/trainingRecords/config/columns";
import {
  mapOptions,
  dialogOptions,
  mapListFilters,
} from "@/views/secure/archives/trainingRecords/config/filters";
import {
  FormRules,
  ElMessage,
  UploadInstance,
  ElMessageBox,
  ElText,
} from "element-plus";

import { useStore } from "vuex";

const tableHeight = ref(window.innerHeight - 498)
const loading = ref(false);
const stores = useStore();
const organTree = stores.state.user.organTree; // 获取树
const isdialogOptions = ref(dialogOptions);
const ismapOptions = ref(mapOptions);
const ismapListFilters = ref(mapListFilters);
const thresholdDialogVisible = ref(false);
const addDialogVisible = ref(false);
const saveDialogVisible = ref(false);
const timer = ref();
const addTilte = ref(""); // 弹出框名称
const houseId = ref("");
// 最近一次维保-年
const year = ref(null);
// 最近一次维保-月
const month = ref(null);
// 最近一次维保-日
const day = ref(null);
// 存放需要维护提醒的 id
const remindList = ref([]);
// 分页和数据展示参数
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tabledata = ref([]);
const search = ref({
  unitName:null,
  trainingTopic:null,
  date:null,
  isState:null,
  trainingDate:null,
  isFile:null
});
const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
  pageCount:
    Math.ceil(total.value / pageSize.value) === 0
      ? 1
      : Math.ceil(total.value / pageSize.value),
}));

// 新增弹框点击消失
const cancelAdd = () => {
  centerDialogVisibleAdd.value = false
  getData()
}

// 编辑弹框点击消失
const cancelEdit = () => {
  centerDialogVisibleEdit.value = false
  getData()
}

// 查看弹框点击消失
const cancelCheck = () => {
  centerDialogVisibleCheck.value = false
}

// 审核弹框点击消失
const cancelExamine = () => {
  centerDialogVisibleExamine.value = false
  getData()
}

const handleShowAdd = () => {
  centerDialogVisibleAdd.value = false
}

const handleShowEdit = () => {
  centerDialogVisibleEdit.value = false
}

const handleShowCheck = () => {
  centerDialogVisibleCheck.value = false
}

const handleShowExamine = () => {
  centerDialogVisibleExamine.value = false
}
// 单位列表数据
const info = ref()
// 获取所有的单位
const getUnitListData = async () => {
  getUnitList().then((res) => {
    console.log('获取所有的单位')
    console.log(res)
    info.value = res;
  }).catch(() => {
    ElMessage.error('获取单位失败');
  });
}
getUnitListData()

// 审核、编辑、查看弹窗数据
const data = ref()
// 新增弹窗是否打开
const centerDialogVisibleAdd = ref(false)
// 编辑弹窗是否打开
const centerDialogVisibleEdit = ref(false)
// 查看是否打开
const centerDialogVisibleCheck = ref(false)
// 审核弹窗是否打开
const centerDialogVisibleExamine = ref(false)
//添加
const openAddDialog = () => {
  centerDialogVisibleAdd.value = true
}
// 校验规格参数
const validateRule = ref();
/**
 * @functionName 分页、查询、排序、删除功能
 * @author fzx
 * @date 2023-12-15
 * @version V1.0.0
 */
const changeCurrent = (value: number) => {
  current.value = value;
  getData();
};
const changePageSize = (size: number) => {
  pageSize.value = size;
  getData();
};
const order = ref([
  {
    column: "state",
    method: "asc",
  },
  {
    column: "lastUpdateTime",
    method: "desc",
  },
]);
/**
 * @functionName 获取数据
 * @author fzx
 * @date 2023-12-15
 * @version V1.0.0
 * @return
 */
const getData = async () => {
  loading.value = true
  const searchList = {
    unitName: search.value?.unitName,
    trainingTopic: search.value?.trainingTopic,
    startTime: search.value?.date?.[0],
    endTime: search.value?.date?.[1],
    isState: search.value?.isState,
    trainingDate: search.value?.trainingDate,
    isFile: search.value?.isFile,
  };
  const playout = {
    pageNum: current.value,
    pageSize: pageSize.value,
    condition: searchList,
  };
  getListPage(playout).then((res) => {
    console.log("xxxxxxxxxxx")
    console.log(res)
    loading.value = false
    tabledata.value = res?.data?.list;
    total.value = res?.data?.total;
  });
};
/**
 * @functionName 排序事件
 * @param {any} data 传入的某一列的列名和升降序
 * @author 彭庆楠
 * @date 2023-08-17 17:48:41
 * @version V1.0.0
 * @return
 */
const sortChange = (data: any) => {
  const method = data.order === "ascending" ? "asc" : "desc";
  order.value[0].column = data.prop;
  order.value[0].method = method;
  getData();
};
// 删除
const DeletRow = (row: any) => {
  deleteTrainingRecords(row).then((res) => {
    if (res?.code) {
      getData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    } else {
      ElMessage.error("删除失败");
    }
  });
};
const CacheState = JSON.parse(
  window.localStorage.getItem("CacheState") as string
);
const name = ref("");
const userId = ref("");
const organId = ref("");
const organName = ref("");
name.value = CacheState.user.userInfo.name;
userId.value = CacheState.user.userInfo.userId;
organId.value = CacheState.user.userInfo.organId;
organName.value = CacheState.user.userInfo.organName;
// 获取当前时间
const getNowFormatDate = () => {
  const date = new Date();
  const year = date.getFullYear().toString();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}
/**
 * @functionName 导出
 * @author fzx
 * @date 2023-12-19
 * @version V1.0.0
 * @return
 */
const handleCreate = (val: any) => {
  const dateNumber = getNowFormatDate();
  // 导出
  exportPageList(search?.value).then((res) => {
    const a = document.createElement("a");
    a.href = URL.createObjectURL(new Blob([res]));
    a.download = "安全培训记录管理" + dateNumber + ".xlsx";
    a.click();
  });
};
const handleEdit = async (row: any) => {
  console.log(row)
  centerDialogVisibleEdit.value = true
  data.value = row;
};
const handleCheck = async (row: any) => {
  console.log(row)
  centerDialogVisibleCheck.value = true
  data.value = row;
};
const handleExamine = async (row: any) => {
  console.log(row)
  centerDialogVisibleExamine.value = true
  data.value = row;
};
const vcoordinate = ref([]) as any;
//addNewData 新增是表单里的数据
const addNewData = ref({});
const FilterRef = ref({});
const linkUserName = ref("");
const linkUserId = ref("");
const handleUserInfo = async (value: any, link: any) => {
  const params = ref({
    groupIds: [] as any,
  });
  params.value.groupIds.length = 0;
  params.value.groupIds.push(value);
  // const a = ref("");
  await getUserInfo(params.value).then((resp) => {
    resp.data.forEach((d: any) => {
      if (d.userId === link) {
        linkUserName.value = d.userName;
        linkUserId.value = d.userId;
      } else if (d.userName === link) {
        linkUserName.value = d.userName;
        linkUserId.value = d.userId;
      }
    });
  });
  // linkUserName.value = a.value;
};

/**
 * @functionName 重置功能
 * @param {FilterDataType} data
 * @description
 * @author 杜思成
 * @date 2023-08-17 17:55:57
 * @version V1.0.0
 * @return
 */
const searchReset = (data: FilterDataType) => {
  search.value = data;
  pager.value.currentPage = 1;
  pager.value.pageSize = 10;
  getData();
};

onBeforeMount(() => {
  getData();
});
</script>
<style scoped>
.maintenance {
  ::v-deep .select-trigger {
    left: -124px;
    right: 20px;
    position: absolute;
  }
  ::v-deep .el-form-item__label {
    width: 110px !important;
  }
}

.link-btn{
  color: #2F7DF1;
}

.link-btns{
  color:#F24A45;
}

</style>
